﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TopVisionVideoStream;
using System.Linq;

namespace RestAPI
{
    public class MUploadfile : RestAPIModelBase
    {
        private MultiPartFormUpload client = new MultiPartFormUpload();

        public event EventHandler<UploadProgressChangedEventArgs> UploadProgressChanged
        {
            add { client.UploadProgressChanged += value; }
            remove { client.UploadProgressChanged -= value; }
        }

        public event EventHandler<UploadDataCompletedEventArgs> UploadDataCompleted
        {
            add { client.UploadDataCompleted += value; }
            remove { client.UploadDataCompleted -= value; }
        }


        private string requestUrl;
        public string RequestUrl
        {
            get
            {
                if (requestUrl == "")
                    requestUrl = RestAPICommon.ServerPath + "/" + RestAPICommon.Services + "/" + "uploadfile";
                return requestUrl;
            }
            set { requestUrl = value; }
        }
        //private string requestUrl => "http://127.0.0.1:9080";

        private FileInfo fileInfo;

        public MUploadfile(string companyid, string account, string filename)
        {
            Companyid = companyid;
            Loginname = account;
            fileInfo = new FileInfo(filename);
            Filename = fileInfo.Name;
        }

        public void UploadAsync()
        {

            ////WebClient client = new WebClient();
            ////NameValueCollection nvc = new NameValueCollection();
            ////nvc.Add("companyid", Companyid);
            ////nvc.Add("loginname", Loginname);
            ////nvc.Add("filename", Filename);
            ////nvc.Add("digest",);

            //MultiPartFormUpload client = new MultiPartFormUpload();

            NameValueCollection bodys = new NameValueCollection();
            var pDic = this.GetDictionaryByModel();
            string digset = RestAPICommon.GetDigset(pDic);
            bodys.Add("companyid", Companyid);
            bodys.Add("loginname", Loginname);
            bodys.Add("filename", Filename);
            bodys.Add("digest", digset);
            client.UploadAsync(RequestUrl, new NameValueCollection() { }, bodys, fileInfo);

            //HttpRequestClient client = new HttpRequestClient();
            //client.SetFieldValue("companyid", Companyid);
            //client.SetFieldValue("loginname", Loginname);
            //client.SetFieldValue("filename", Filename);
            //client.SetFieldValue("digest", digset);
            //client.SetFieldValue("file", fileInfo.Name, FileContentType.GetMimeType(Path.GetExtension(Filename)), File.ReadAllBytes(fileInfo.FullName));

            //string response = "";

            //var webc = client.UploadAsync(requestUrl, out response);

            //Console.WriteLine(response);

            //return webc;
        }

        public void UploadAsync(NameValueCollection nameValues)
        {
            NameValueCollection bodys = new NameValueCollection();
            var pDic = this.GetDictionaryByModel();
            string digset = RestAPICommon.GetDigset(pDic);

            foreach (var item in nameValues.AllKeys)
            {
                bodys.Add(item, nameValues[item]);
            }

            client.UploadAsync(RequestUrl, new NameValueCollection() { }, bodys, fileInfo);

        }

        //public async void ClientPost()
        //{
        //    var pDic = this.GetDictionaryByModel();

        //    string digset = RestAPICommon.GetDigset(pDic);

        //    HttpClientHandler hch = new HttpClientHandler();

        //    //ProcessHandler processHandler = new ProcessHandler();
        //    HttpMessage hand = new HttpMessage(hch);

        //    HttpClient client = new HttpClient(hand);

        //    MultipartFormDataContent form = new MultipartFormDataContent();

        //    HttpContent content = new StringContent(Companyid, Encoding.UTF8);
        //    form.Add(content, "companyid");

        //    content = new StringContent(Loginname, Encoding.UTF8);
        //    form.Add(content, "loginname");

        //    content = new StringContent(Filename, Encoding.UTF8);
        //    form.Add(content, "filename");

        //    content = new StringContent(digset, Encoding.UTF8);
        //    form.Add(content, "digest");

        //    var fileStream = new FileStream(fileInfo.FullName, FileMode.Open);

        //    StreamContent fileContent = new StreamContent(fileStream);

        //    fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
        //    {
        //        Name = "file",
        //        FileName = fileInfo.FullName
        //    };

        //    form.Add(fileContent);

        //    var responseMessage = await client.PostAsync(requestUrl, form);

        //    Console.WriteLine(await responseMessage.Content.ReadAsStringAsync());

        //    fileStream.Close();

        //    client.Dispose();
        //}

        //public string HttpPostData(string url, int timeOut, string fileKeyName,
        //                            string filePath, NameValueCollection stringDict)
        //{
        //    string responseContent;
        //    var memStream = new MemoryStream();
        //    var webRequest = (HttpWebRequest)WebRequest.Create(url);
        //    // 边界符
        //    var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
        //    // 边界符
        //    var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
        //    var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
        //    // 最后的结束符
        //    var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");

        //    // 设置属性
        //    webRequest.Method = "POST";
        //    webRequest.Timeout = timeOut;
        //    webRequest.ContentType = "multipart/form-data; boundary=" + boundary;

        //    // 写入文件
        //    const string filePartHeader =
        //        "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
        //         "Content-Type: application/octet-stream\r\n\r\n";
        //    var header = string.Format(filePartHeader, fileKeyName, filePath);
        //    var headerbytes = Encoding.UTF8.GetBytes(header);

        //    memStream.Write(beginBoundary, 0, beginBoundary.Length);
        //    memStream.Write(headerbytes, 0, headerbytes.Length);

        //    var buffer = new byte[1024];
        //    int bytesRead; // =0

        //    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
        //    {
        //        memStream.Write(buffer, 0, bytesRead);
        //    }

        //    // 写入字符串的Key
        //    var stringKeyHeader = "\r\n--" + boundary +
        //                           "\r\nContent-Disposition: form-data; name=\"{0}\"" +
        //                           "\r\n\r\n{1}\r\n";

        //    foreach (byte[] formitembytes in from string key in stringDict.Keys
        //                                     select string.Format(stringKeyHeader, key, stringDict[key])
        //                                         into formitem
        //                                     select Encoding.UTF8.GetBytes(formitem))
        //    {
        //        memStream.Write(formitembytes, 0, formitembytes.Length);
        //    }

        //    // 写入最后的结束边界符
        //    memStream.Write(endBoundary, 0, endBoundary.Length);

        //    webRequest.ContentLength = memStream.Length;

        //    var requestStream = webRequest.GetRequestStream();

        //    memStream.Position = 0;
        //    var tempBuffer = new byte[memStream.Length];
        //    memStream.Read(tempBuffer, 0, tempBuffer.Length);
        //    memStream.Close();

        //    requestStream.Write(tempBuffer, 0, tempBuffer.Length);
        //    requestStream.Close();

        //    var httpWebResponse = (HttpWebResponse)webRequest.GetResponse();

        //    using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(),
        //                                                    Encoding.GetEncoding("utf-8")))
        //    {
        //        responseContent = httpStreamReader.ReadToEnd();
        //    }

        //    fileStream.Close();
        //    httpWebResponse.Close();
        //    webRequest.Abort();

        //    return responseContent;
        //}

        public void Cancel()
        {

        }
    }

    class HttpMessage : MessageProcessingHandler
    {
        public HttpMessage(HttpMessageHandler innerHandler) : base(innerHandler)
        {
            InnerHandler = innerHandler;
        }

        protected override HttpRequestMessage ProcessRequest(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            return request;
        }

        protected override HttpResponseMessage ProcessResponse(HttpResponseMessage response, CancellationToken cancellationToken)
        {
            return response;
        }
    }
}
